#include<iostream>

using namespace std;

int A[100],B[100],LCM;

int gcd(int a,int b)
{
	return b==0?a:gcd(b,a%b);
}

int lcm(int a,int b)
{
	return a*b/gcd(a,b);
}

void exgcd(int a,int b,int &d,int &x, int &y)
{
	if(b==0)
	{
		d=a;
		x=1;
		y=0;
		return;
	}
	exgcd(b,a%b,d,x,y);
	int temp=x;
	x=y;
	y=temp-a/b*y;
}

int solve(int m)
{
	int a1,a2,r1,r2,c,x0,y0,d,a,b;
	a1=A[1];r1=B[1];
	LCM=a1;
	bool flag=true;
	for(int i=2;i<=m;i++)
	{
		a2=A[i];r2=B[i];
		a=a1;b=a2;c=r2-r1;
		LCM=lcm(LCM,a2);
		exgcd(a,b,d,x0,y0);
		if(c%d!=0)
		{
			flag=false;
		}
		int t=b/d;
		x0=(x0*(c/d)%t+t)%t;
		r1=a1*x0+r1;
		a1=a1*(a2/d);
	}
	if(!flag)
	{
		r1=-1;
	}
	return r1;
}

int main()
{
	int T;
	cin>>T;
	for(int cas=1;cas<=T;cas++)
	{
		int M;
		cin>>M;
		for(int i=1;i<=M;i++)cin>>A[i];
		for(int i=1;i<=M;i++)cin>>B[i];
		int res=solve(M);
		if(res==0)res+=LCM;
		cout<<"Case "<<cas<<": "<<res<<endl;
	}
	return 0;
}
